#include "threadPool.h"
#define  MAX_PATH_LEN 1024
int netDriveCd(char* pathname, const char* dirname, int netfd) {
    char new_path[MAX_PATH_LEN];

    if (strcmp(dirname, ".") == 0) {
        // 不需要改变目录
    }
    else if (strcmp(dirname, "..") == 0) {  // 切换到上一级目录
        for(int i=strlen(pathname);i>0;--i){
            if(new_path[i]!='/'){
                new_path[i]='\0';
            }else{
                new_path[i]='\0';
                train_t train;
                strcpy(pathname,new_path);
                train.len=strlen(pathname);
                memcpy(train.data,pathname,train.len);
                send(netfd,&train,sizeof(int)+train.len,MSG_NOSIGNAL);
                break;
            }
        }
    }
    else {  // 切换到指定目录
        if (dirname[0] == '/') {  // 绝对路径
            strcpy(new_path, dirname);
        }
        else {  // 相对路径
            sprintf(new_path,"%s/%s",pathname,dirname);
        }
        DIR * pdir=opendir(new_path);
        printf("%s\n",new_path);
        if (pdir==NULL&&errno==ENOENT) {  //失败
            train_t train;
            char error_msg[MAX_PATH_LEN + 12];
            sprintf(error_msg, "cd: %s: No such file or directory\n", dirname);
            train.len=strlen(error_msg);
            memcpy(train.data,error_msg,train.len);
            send(netfd,&train,sizeof(int)+train.len,MSG_NOSIGNAL);
        }
        else {  // 成功
            train_t train;
            strcpy(pathname,new_path);
            train.len=strlen(pathname);
            memcpy(train.data,pathname,train.len);
            send(netfd,&train,sizeof(int)+train.len,MSG_NOSIGNAL);
        }
    }

    return 0;
}
